package com.itzgyw.example.controller;

import com.itzgyw.cache.annotation.Reload;
import com.itzgyw.cache.annotation.ReloadData;
import com.itzgyw.cache.annotation.ReloadElement;
import com.itzgyw.example.dao.UserDao;
import com.itzgyw.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/12/10 17:48
 * @Description: 暂无描述
 */
@Component
public class UserService {
    @Autowired
    private UserDao userDao;


    public User findById(Integer id) {
        return userDao.findById(id).orElseGet(() -> null);
    }


    @Cacheable(value = {"http:data"}, key = "#id")
    public User get(Integer id) {
        return findById(id);
    }

    @Cacheable(value = {"http:data:list"}, key = "#page+'-'+#size")
    public List<User> list(Integer page, Integer size) {
        Page<User> users = userDao.findAll(PageRequest.of(page, size));
        return users.getContent();
    }

    @Cacheable(value = {"http:data:page"}, key = "#page+'-'+#size")
    public Page<User> page(Integer page, Integer size) {
        Page<User> users = userDao.findAll(PageRequest.of(page, size));
        return users;
    }


    @CachePut(value = "http:data", key = "#user.id")
    public User update1(User user) {
        userDao.saveAndFlush(user);
        return user;
    }

    @Reload(data = {
            @ReloadData(reloadClass = User.class, reloadName = "http:data:list", reloadBeanName = "userService", reloadMethodName = "list"),
            @ReloadData(reloadClass = User.class, reloadName = "http:data:page", reloadBeanName = "userService", reloadMethodName = "page")
    })
    public void insert(User user) {
        userDao.save(user);
        userDao.flush();
    }

    @Reload(data = {
            @ReloadData(reloadClass = User.class, reloadName = "http:data:list", reloadBeanName = "userService", reloadMethodName = "list"),
            @ReloadData(reloadClass = User.class, reloadName = "http:data:page", reloadBeanName = "userService", reloadMethodName = "page")
    }, element = @ReloadElement(reloadClass = User.class, reloadName = "http:data", reloadKey = "#id"))
    public void delete(Integer id) {
        userDao.deleteById(id);
    }
}
